package feizhou.untils.tools;

import java.util.concurrent.*;

/**
 * 
 * 线程池工具
 * @author  <a href="920786312@qq.com">周飞</a>
 * @since 2023/8/22 12:01
 */
public class ExecuteThreadPoolUtil {
    private static ExecutorService executorService;

    private ExecuteThreadPoolUtil() {
    }

    //默认内存线程池
    static {
        final int[] count = {0};
        executorService = Executors.newCachedThreadPool(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "cache_thread_pool-" + count[0]++);
            }
        });
    }

    public static void execute(Runnable runnable) {
        executorService.execute(runnable);
    }

    /**
     * @Author feizhou
     * @Description  用于处理不是很大的并发量，而是平缓的流入速度，比如用于定时任务
     *  允许核心线程数在没有任务的时候退出
     * @Date 13:48 2019/9/3
     * @Param corePoolSize：cpu内核数+1（当前cpu内核数为16）
     * @Param maximumPoolSize：最大线程数 corePoolSize*1.5
     * @Param keepAliveTime ：单位是秒，空闲线程
     * @Param workQueue：阻塞队列
     * @Param handler：拒绝策略
     * @return java.util.concurrent.ExecutorService
     **/
    public static ExecutorService getExecutorService(int corePoolSize,
                                                     int maximumPoolSize,
                                                     long keepAliveTime,
                                                     BlockingQueue<Runnable> workQueue,
                                                     RejectedExecutionHandler handler) {
        ThreadPoolExecutor pool = new ThreadPoolExecutor(corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                workQueue,
                handler);
        pool.allowCoreThreadTimeOut(true);
        return pool;
    }

}
